package com.yylending.las.deviceinfo;

import com.google.gson.Gson;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import com.yylending.las.common.AESEntity;
import com.yylending.las.Constants;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import rx.Subscriber;
import rx.functions.Action0;

import java.net.ConnectException;

/**
 * Created by laixj on 2016/11/17.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class UploadDevicePresenter extends Presenter<UploadDeviceModel, UploadDevicePresenter.View> {
	private final static String TAG = "UploadDevicePresenter";

	public interface View extends IView {
		/**
		 * 上传设备信息
		 *
		 * @param evalPath
		 * @param result
		 */
		void uploadSuccess(String evalPath, String result);

		/**
		 * 上传设备信息
		 *
		 * @param evalPath
		 * @param result
		 */
		void uploadFail(String evalPath, String result);
	}

	public static class Generator implements PresenterFactory<UploadDevicePresenter> {
		@Override
		public UploadDevicePresenter create() {
			return new UploadDevicePresenter();
		}
	}

	private View mView;
	private String mRequestPage;

	@Override
	public void attach(View view) {
		mRequestPage = view.getClass().getName();
		mView = view;
		mModel = new UploadDeviceModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	/**
	 * 上传App信息
	 *
	 * @param apps
	 */
	public void uploadAppInfo(final UploadDeviceModel.UploadApp apps) {
		if (null != apps) {
			CLog.i(TAG, "uploadAppInfo apps=" + apps.softwareList.size() + ",apps.toString()=" + (new Gson().toJson(apps)));
		}
		execute(new AESEntity(apps), UploadDeviceModel.METHOD_UPLOAD_APP_INFO, false, Constants.EVALPATH_SOFTWARE, mRequestPage);
	}

	/**
	 * 上传通话记录
	 *
	 * @param callLogs
	 */
	public void uploadCalLogs(final UploadDeviceModel.UploadCallLog callLogs) {
		if (null != callLogs) {
			CLog.i(TAG, "uploadCalLogs callLogs=" + callLogs.callRecordList.size() + ",callLogs.toString()=" + (new Gson().toJson(callLogs)));
		}
		execute(new AESEntity(callLogs), UploadDeviceModel.METHOD_UPLOAD_CALL_LOG, false, Constants.EVALPATH_CALL, mRequestPage);
	}

	/**
	 * 上传短信信息
	 *
	 * @param smsInfo
	 */
	public void uploadSmsInfo(final UploadDeviceModel.UploadSms smsInfo) {
		if (null != smsInfo) {
			CLog.i(TAG, "uploadSmsInfo smsList=" + smsInfo.smsInfoList.size() + ",smsList.toString()=" + (new Gson().toJson(smsInfo)));
		}
		execute(new AESEntity(smsInfo), UploadDeviceModel.METHOD_UPLOAD_SMS, false, Constants.EVALPATH_SMS, mRequestPage);
	}

	/**
	 * 上传通讯录
	 *
	 * @param contacts
	 */
	public void uploadContacts(final UploadDeviceModel.UploadContact contacts) {
		if (null != contacts) {
			CLog.i(TAG, "uploadContacts contactList=" + (new Gson().toJson(contacts)));
		}
		execute(new AESEntity(contacts), UploadDeviceModel.METHOD_UPLOAD_CONTACT, false, Constants.EVALPATH_CONTACT, mRequestPage);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void uploadSmsResult(UploadDeviceModel.UploadSmsResult result) {
		if (mRequestPage.equals(result.requestPage)) {
			CLog.i(TAG, "uploadSmsResult111 =" + result.toString());
			if (BaseResultEntity.isResponseSuccess(result)) {
				mView.uploadSuccess((String)result.extraParam, result.getRetMsg());
			} else {
				mView.uploadFail((String)result.extraParam, "上传失败");
			}
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void uploadAppInfoResult(UploadDeviceModel.UploadAppInfoResult result) {
		if (mRequestPage.equals(result.requestPage)) {
			CLog.i(TAG, "uploadAppInfoResult111=" + result.toString());
			if (BaseResultEntity.isResponseSuccess(result)) {
				mView.uploadSuccess((String)result.extraParam, result.getRetMsg());
			} else {
				mView.uploadFail((String)result.extraParam, "上传失败");
			}
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void uploadCallLogResult(UploadDeviceModel.UploadCallLogResult result) {
		if (mRequestPage.equals(result.requestPage)) {
			CLog.i(TAG, "uploadCallLogResult111 =" + result.toString());
			if (BaseResultEntity.isResponseSuccess(result)) {
				mView.uploadSuccess((String)result.extraParam, result.getRetMsg());
			} else {
				mView.uploadFail((String)result.extraParam, "上传失败");
			}
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void uploadContactResult(UploadDeviceModel.UploadContactResult result) {
		if (mRequestPage.equals(result.requestPage)) {
			CLog.i(TAG, "uploadContactResult111 =" + result.toString());
			if (BaseResultEntity.isResponseSuccess(result)) {
				mView.uploadSuccess((String)result.extraParam, result.getRetMsg());
			} else {
				mView.uploadFail((String)result.extraParam, "上传失败");
			}
		}
	}

	/**
	 * 请求数据，数据源可以是网络、内存、硬盘或其他，调用者不需要关心<br>
	 * 当满足以下五个条件时使用：
	 * 1.Presenter包含多个请求，需要显式指定过程标识<br>
	 * 2.View需要自定义的请求过程提醒才能满足需求，
	 * 3.View可以按需重写{@link IView}的onFunctionalStart(boolean autoTips)、onFunctionalCompleted(boolean autoTips)、onFunctionalError(Throwable e, boolean autoTips)方法<br>
	 * 4.Presenter需要根据某些参数区分请求
	 * 5.Presenter需要根据请求页面判断是否需要回调
	 *
	 * @param params         请求参数（公共参数除外）
	 * @param functionalCode 过程标识
	 * @param autoTips       是否使用默认的请求过程提醒
	 * @param extraParam     需要返回的参数
	 * @param requestPage    发送请求的页面
	 */
	@SuppressWarnings("unchecked")
	public void execute(Object params, final int functionalCode, final boolean autoTips, final Object extraParam, final String requestPage) {
		if (!com.yyfax.infrastructure.Constants.isConnected){//如果没有网络
			super.onError(new ConnectException(), autoTips, functionalCode);
			return;
		}
		mModel.execute(params, functionalCode, extraParam, requestPage)
				.doOnUnsubscribe(new Action0() {
					@Override
					public void call() {
						CLog.i(TAG, "Unsubscribe in " + getClass().getSimpleName());
					}
				})
				//.compose(mBaseView.composeLifecycle())//在操作符之后绑定才能生效
				.subscribe(new Subscriber<BaseResultEntity>() {//数据回调
					@Override
					public void onStart() {
						CLog.e(TAG, "new Subscriber: onStart");
						UploadDevicePresenter.this.onStart(autoTips);
					}

					@Override
					public void onNext(final BaseResultEntity o) {
						CLog.e(TAG, "new Subscriber: onNext");
						UploadDevicePresenter.this.onNext(o);
					}

					@Override
					public void onCompleted() {
						CLog.e(TAG, "new Subscriber: onCompleted");
						UploadDevicePresenter.this.onCompleted(autoTips);
						unsubscribe();
					}

					@Override
					public void onError(Throwable e) {
						CLog.e(TAG, "new Subscriber: onError => " + e.getMessage());
						UploadDevicePresenter.this.onError(e, autoTips, functionalCode);
						unsubscribe();
					}
				});
	}

	public void onStart(boolean autoTips) {
		//super.onStart(autoTips);
	}

	@SuppressWarnings("unchecked")
	public void onNext(BaseResultEntity t) {
		//mModel.onNext(t);
		//detach();
		CLog.i(TAG, "上传信息-->"+t.toString());
	}

	public void onCompleted(boolean autoTips) {
		//mView.onFunctionalCompleted(autoTips);
	}

	public void onError(Throwable e, boolean autoTips, int functionalCode) {
		detach();
		//mView.onFunctionalError(e, autoTips, functionalCode);
	}
}
